<template>
    <ul class="list">
        <li v-for="product in products" :key="product.id">
            {{product.title}} ----- {{product.price | currency }}
            <br>
            <el-button :disabled="!product.inventory" @click="addToCart(product)">加入购物车</el-button>
        </li>
    </ul>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { Getter, Action } from 'vuex-class'
import { Product } from '@/store'

@Component
export default class ProductList extends Vue {
    // 从state中获取products数据
    @Getter('allProducts')
    public products!: Product[];
    // 加入购物车，这里用的是全局的action
    @Action('addToCart')
    public actionAddToCart!: any;
    // 获取数据的action
    @Action('getAllProducts')
    public getAllProducts!: any;

    public addToCart (product: Product) {
        this.actionAddToCart(product)
    }
    // 发送请求，获取products数据
    public created () {
        this.getAllProducts()
    }
}
</script>

<style lang="scss" scoped>
    ul {
        list-style-type: none;
        padding-left: 0;
    }

    .list {
    li {
        padding: 5px 0;
        display: flex;
        justify-content: center;
        align-items: center;
        button {
            margin-left: 20px;
        }
    }
    }
</style>
